{
 "metadata": {
  "name": "",
  "signature": "sha256:7099f6b92fc0565eed312f9d9ebeb1c4b739297812b3df9baeace3785a17271d"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>"
     ]
    },
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Financial Time Series Visualization &mdash; plotly"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "**PyData London 2015**"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Yves Hilpisch\n",
      "\n",
      "<a href='mailto:team@tpq.io'>team@tpq.io</a> | <a href='http://tpq.io'>http://tpq.io</a>\n",
      "\n",
      "The Python Quants GmbH"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "##Cufflinks\n",
      "\n",
      "This library binds the power of [plotly](http://www.plot.ly) with the flexibility of [pandas](http://pandas.pydata.org/) for easy plotting. This library is available on https://github.com/santosjorge/cufflinks. You can easily `pip install` it. The code of this IPython Notebook is mainly from Jorge Santos.\n",
      "\n",
      "The following assumes that the plotly user credentials have already been configured as stated on the [getting started](https://plot.ly/python/getting-started/) guide. Alternatively, the demo account credentials can be used (see below)."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import plotly.plotly as py\n",
      "import pandas as pd\n",
      "import pandas.io.data as web\n",
      "import cufflinks as cf\n",
      "import numpy as np"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "py.sign_in('Python-Demo-Account', 'gwt101uhh0')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "We retrieve adjusted historical closing prices for a number of symbols."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "symbols = ['IBM', 'MSFT', 'AAPL', ]"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df = pd.DataFrame()\n",
      "for sym in symbols:\n",
      "    data = web.DataReader(sym, data_source='yahoo')\n",
      "    df[sym] = data['Adj Close']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "**iplot** can be used on any DataFrame to plot on a plotly chart. If no filename is specified then a generic *Plotly Playground* file is created. All the charts are created as private by default. To make them public you can use **world_readable=True**. Let's look at the avilable parameters."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "help(df.iplot)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.iplot(filename='fin_time_series_1', world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Pretty Printing Figures\n",
      "\n",
      "**iplot** can return a static *Plotly Figure* if we state **asFigure=True**. "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "fig=df.iplot(filename='fin_time_series_1', world_readable=True, asFigure=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Cufflinks also provides a pretty print **pp** function that makes any object of type dictionary (figures,layouts) better readable."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "cf.pp(fig['layout'])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Customizing Themes\n",
      "\n",
      "We can pass a **theme** to the **iplot** function. \n",
      "3 themes are available, but you can create your own\n",
      "* Solar\n",
      "* Pearl (Default)\n",
      "* White"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.iplot(theme='white', filename='fin_time_series_2', world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "We can also pass common metadata for the chart, like title."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.iplot(theme='pearl', filename='fin_time_series_3', title='Stock Returns',\n",
      "         xTitle='Return', yTitle='Dates', world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Bestfit Lines\n",
      "\n",
      "We can easily add a bestfit line to any Series\n",
      "\n",
      "This will automatically add a best fit approximation and the equation as the legend."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df['IBM'].iplot(filename='fin_time_series_4', bestfit=True, world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Customizing Colors\n",
      "\n",
      "We can pass any color (either by Hex, RGB or Text *)  \n",
      "\n",
      "*Text values are specified in the cufflinks.colors modules"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df['IBM'].iplot(filename='fin_time_series_5', bestfit=True, colors=['pink'],\n",
      "                bestfit_colors=['blue'], world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Filled Traces\n",
      "\n",
      "We can add a fill to a trace with **fill=True**"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df['MSFT'].iplot(filename='fin_time_series_7',\n",
      "                 fill=True,colors=['green'], world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Bar Charts\n",
      "\n",
      "We can easily create a bar chart with the parameter **kind**"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.sum().iplot(kind='bar', filename='fin_time_series_9', world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Bars can also be stacked by a given dimension"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.resample('M').iplot(kind='bar', barmode='stacked', world_readable=True,\n",
      "                       filename='fin_time_series_10')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Spread and Ratio charts\n",
      "\n",
      "We can also create spread and ratio charts on the fly with **kind='spread'** and **kind='ratio'**."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df[['IBM', 'MSFT']].iplot(filename='fin_time_series_11', kind='spread',\n",
      "                         world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df[['IBM', 'MSFT']].iplot(filename='fin_time_series_12', kind='ratio',\n",
      "                         colors=['green','red'], world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Annotations\n",
      "\n",
      "Annotations can be added to the chart and these are automatically positioned correctly. **Annotations** should be specified in dictionary form."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "annotations={'2013-01-15':'Dividends', '2014-03-31':'Split Announced'}\n",
      "df['MSFT'].iplot(filename='fin_time_series_13', annotations=annotations,\n",
      "                 world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Output as Image\n",
      "\n",
      "The output of a chart can be in an image mode as well. For this we can use `asImage=True`. We can also set the dimensions (optional) with `dimensions=(width,height)`."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df[['MSFT', 'AAPL']].iplot(filename='fin_time_series_14', theme='white', \n",
      "                          colors=['pink','blue'], asImage=True, \n",
      "                          dimensions=(800, 500), world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Advanced Use\n",
      "\n",
      "It is also possible to get the Plotly Figure as an output to tweak it manually. We can achieve this with `asFigure=True`."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df['MSFT'].iplot(asFigure=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "We can also get the **Data** object directly"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "data = df.to_iplot()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "data[0]['name']='My Custom Name'"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "And pass this directly to **iplot**"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "df.iplot(data=data, filename='fin_time_series_15', world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>\n",
      "\n",
      "<a href=\"http://tpq.io\" target=\"_blank\">http://tpq.io</a> | <a href=\"http://twitter.com/dyjh\" target=\"_blank\">@dyjh</a> | <a href=\"mailto:team@pqp.io\">team@tpq.io</a>\n",
      "\n",
      "**Quant Platform** |\n",
      "<a href=\"http://quant-platform.com\">http://quant-platform.com</a>\n",
      "\n",
      "**datapark.io** |\n",
      "<a href=\"http://datapark.io\">http://datapark.io</a>\n",
      "\n",
      "**Python for Finance** |\n",
      "<a href=\"http://python-for-finance.com\" target=\"_blank\">Python for Finance @ O'Reilly</a>\n",
      "\n",
      "**Derivatives Analytics with Python** |\n",
      "<a href=\"http://derivatives-analytics-with-python.com\" target=\"_blank\">Derivatives Analytics @ Wiley Finance</a>"
     ]
    }
   ],
   "metadata": {}
  }
 ]
}